<?php

if (!defined('BASEPATH'))
    exit('No direct script access allowed');

/**
 *  Category Model Class  
 *  
 * @package XGO CMS v2.0 
 * @subpackage News  
 * @author Manh Nguyen - 31/07/2012 
 * @link http://sunsoft.vn
 */
class Category_model extends DataMapper {

    var $model = 'category_model';
    var $table = 'category';

    // --------------------------------------------------------------------
    // Construct
    // --------------------------------------------------------------------
    function __construct() {
        parent::__construct();
    }

    // --------------------------------------------------------------------
    // Relationships
    // --------------------------------------------------------------------
    //var $has_many = array('comment');
    var $has_many = array(
        'news' => array(
            'class' => 'news_model',
            'other_field' => 'category'
        )
    );
    //var $has_one = array('user', 'category');
    //var $has_one = array('category');
    var $has_one = array(
        'creator' => array(
            'class'         => 'user_model',
            'other_field'   => 'created_category'
        ),
        'editor' => array(
            'class'         => 'user_model',
            'other_field'   => 'edited_category'
        )
    );
    // --------------------------------------------------------------------
    // Validation
    // --------------------------------------------------------------------	
    // --------------------------------------------------------------------
    /**
     * Default order in query select 
     */
    var $default_order_by = array('created' => 'desc');

    // --------------------------------------------------------------------
    /**
     * string value of object
     * 
     * @access private
     * @param null
     * @return string 
     */
    function __toString() {
        return empty($this->title) ? '---empty---' : $this->title;
    }

    /**
     * Get list category
     * @param type $limit
     * @return \Category_model
     */
    public function get_list($limit = 20) {
        $category = new Category_model();
        $category->select('id, title, code');
        $category->limit($limit);
        $category->get();

        return $category;
    }

    /**
     * get list category
     * @param type $zero
     * @return type
     */
    function category_list($zero = FALSE) {
        $category = new Category_model();
        $category->select('id, title');

        if ($zero) {
            $category_list = array('' => '---'.$this->lang->line('all').'---');
        } else {
            $category_list = array();
        }

        foreach ($category->get() as $item) {
            $category_list[$item->id] = $item->title;
        }
        return $category_list;
    }

    /**
     * list of id and title of object, user for create options.
     * 
     * @access public
     * @param array get, array para
     * @return void
     */
    public function get_title_parent_id($parent_id) {

        if ($parent_id <= 0)
            return '---'.$this->lang->line('cat')." ".$this->lang->line('root').'---';
        else {
            $this->select('id, title')->where('id', $parent_id)->get(1);
            return $this->title;
        }
    }

    public function get_parent_category($catid)
    {
        $this->select('id, title, code');
        $where = '`id`=(select `category`.`parent_id` from `category` where `category`.`id`='.$catid.')';
        $this->strwhere($where);
        $this->get();//$this->check_last_query();exit;
        return $this;
    }
    
    public function get_title_category_id($category_id) {
        if ($category_id <= 0)
            return '---'.$this->lang->line('cat')." ".$this->lang->line('root').'---';
        else {
            $this->select('id, title, code')->where('id', $category_id)->get(1);//echo $this->check_last_query();
            return $this;
        }
    }
    
    
    public function get_title_by_code($category_code){
    	$this->select('id, title')->where('code', $category_code)->get(1);
    	return $this->title;
    }
    
    
    // --------------------------------------------------------------------
    /**
     * level of object in tree of object.
     * 
     * @access public
     * @param null
     * @return int
     */
    function level() {
        if ($this->id > 0) {
            if ($this->parent_id == 0)
                return 1;
            $cat_obj = new Category_model();
            $cat_obj->select('id, parent_id');
            $cat_obj->where('id', $this->parent_id);
            $cat_obj->get(1);
            return 1 + $cat_obj->level();
        }
        return 0;
    }

    // --------------------------------------------------------------------
    /**
     * list of object are one sub level of this object.
     * 
     * @access public
     * @param array
     * @return objs
     */
    function get_one_sub($para = array()) {
        if ($this->id > 0) {
            $category = new Category_model();
            if (!empty($para['select']))
                $category->select($para['select']);
            $category->where('parent_id', $this->id);
            if (!empty($para['notin_id']))
                $category->where_not_in('id', $para['notin_id']);
            if (!empty($para['type'])) {
                if (is_array($para['type']))
                    $category->where_in('type', $para['type']);
                else
                    $category->where('type', $para['type']);
            }
            return $category->get();
        }
        return new Category_model();
    }

    // --------------------------------------------------------------------
    /**
     * list of object are chile of this object (include level).
     * 
     * @access public
     * @param array get, int, array para
     * @return void
     */
    function get_all_sub(&$list, $level = 1, $para = array()) {
        if (!isset($para['notin_id']))
            $para['notin_id'] = array();
        if ($this->id > 0 && !in_array($this->id, $para['notin_id'])) {
            foreach ($this->get_one_sub($para) as $menu) {
                $menu->level = $level;
                $list[] = $menu;
                $menu->get_all_sub($list, $level + 1, $para);
            }
        }
    }

    // --------------------------------------------------------------------
    /**
     * list of id and title of object, user for create options.
     * 
     * @access public
     * @param array get, array para
     * @return void
     */
    function get_child_id(&$listname, $parameter = array(), $parent_id) {
        $notin_id = array();       
        if (!isset($parameter['check']))
            $check = FALSE;
        else
            $check = $parameter['check'];
        if ($check && $this->id > 0) {
            // Lay danh sach id la cac danh muc con cua danh muc hien tai
            $notin_id[] = $this->id;
            $listobj = array();
            $this->get_all_sub($listobj, 1, array('select' => 'id'));
            foreach ($listobj as $obj) {
                $notin_id[] = $obj->id;
            }
        }
        
        $listname[]=$parent_id;
        $select = 'id';
        $cat_obj = new Category_model();
        $cat_obj->select($select);
        $cat_obj->where('parent_id', $parent_id);
        if (!empty($parameter['type']))
            $cat_obj->where('type', $parameter['type']);
        if (!empty($parameter['language']))
            $cat_obj->where_related('language', 'id', $parameter['language']);
        // Lay tham so gioi han level cua danh muc
        if (!isset($parameter['maxlevel']))
            $maxlevel = 0;
        else
            $maxlevel = $parameter['maxlevel'];
        foreach ($cat_obj->get_iterated() as $o) {
            $listobj = array();
            if (!in_array($o->id, $notin_id)) {
                $o->level = 1;
                $listobj[] = $o;
                $o->get_all_sub($listobj, 2, array('select' => $select));
                foreach ($listobj as $o1) {
                    if ($maxlevel == 0 || $o1->level <= $maxlevel) {
                        $listname[]= $o1->id;
                    }
                }
            }
        }
    }
    // --------------------------------------------------------------------
    /**
     * list of id and title of object, user for create options.
     * 
     * @access public
     * @param array get, array para
     * @return void
     */
    function get_list_title(&$listname, $parameter = array()) {
        $notin_id = array();
        if (!isset($parameter['check']))
            $check = FALSE;
        else
            $check = $parameter['check'];
        if ($check && $this->id > 0) {
            // Lay danh sach id la cac danh muc con cua danh muc hien tai
            $notin_id[] = $this->id;
            $listobj = array();
            $this->get_all_sub($listobj, 1, array('select' => 'id'));
            foreach ($listobj as $obj) {
                $notin_id[] = $obj->id;
            }
        } 
        $select = 'id, title';
        $cat_obj = new Category_model();
        $cat_obj->select($select);
        $cat_obj->where('parent_id', 0);
        if (!empty($parameter['type']))
            $cat_obj->where('type', $parameter['type']);
        if (!empty($parameter['language']))
            $cat_obj->where_related('language', 'id', $parameter['language']);
        // Lay tham so gioi han level cua danh muc
        if (!isset($parameter['maxlevel']))
            $maxlevel = 0;
        else
            $maxlevel = $parameter['maxlevel'];
        foreach ($cat_obj->get_iterated() as $o) {
            $listobj = array();
            if (!in_array($o->id, $notin_id)) {
                $o->level = 1;
                $listobj[] = $o;
                $o->get_all_sub($listobj, 2, array('select' => $select));
                foreach ($listobj as $o1) {
                    if ($maxlevel == 0) {
                        $listname[$o1->id] = $o1->get_title_format();
                    } else {
                        if ($o1->level <= $maxlevel) {
                            $listname[$o1->id] = $o1->get_title_format();
                        }
                    }
                }
            }
        }
    }

    // --------------------------------------------------------------------
    /**
     * string of object's title in formatted.
     * 
     * @access public
     * @param string
     * @return string
     */
    function get_title_format($space = '-') {
        if (!isset($this->level))
            $this->level = $this->level();
        $str = str_repeat($space, $this->level * 5);
        return $str . $this->title;
    }

    function jqgrid_metadata() {
        //edittype: 'text', 'textarea', 'select', 'checkbox', 'password', 'button', 'image', 'file', 'custom'
        $partner = new Partner_model();
        
        $category_list = array(
            '' => '---'.$this->lang->line('all'),
            '0' => '---'.$this->lang->line('cat')." ".$this->lang->line('root')
        );
        
        $this->get_list_title($category_list, TRUE, 2);
        
        return array(
            'names' => array(
                'id',
                $this->lang->line('title'),
                $this->lang->line('parent').' '.strtolower($this->lang->line('cat')),
                $this->localize_label('creator_id'),
                $this->localize_label('created'),
                $this->lang->line('partner_id')
            ),
            'model' => array(
                array('name' => 'id',
                    'hidden' => TRUE,
                    'key' => TRUE,
                    'editrules' => array('edithidden' => TRUE)
                ),
                array('name' => 'title',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'parent_id',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $category_list
                    ),
                    'stype' => 'select'
                ),
                array('name' => 'creator_id',
                    'searchoptions' => array(
                        'sopt' => array('cn', 'nc', 'eq', 'bw', 'bn', 'ew', 'en')
                    )
                ),
                array('name' => 'created',
                    'search' => FALSE
                ),
                array('name' => 'partner_id',
                    'searchoptions' => array(
                        'sopt' => array('eq'),
                        'value' => $partner->partner_list(TRUE)
                    ),
                    'stype' => 'select'
                )
            )
        );
    }
        // --------------------------------------------------------------------
    /**
     * rewite delete function to check relative object before delete. 
     * 
     * @access public
     * @param obj, string
     * @return -1 or -2 or bool
     */
    function delete($object = '', $related_field = '') {
        if (empty($object) && !is_array($object) && $this->id > 0) {
            if ($this->news->count() > 0) {
                return -1;
            }
            $cat_list = $this->get_one_sub(array('select' => 'id'));
            if ($cat_list->result_count() > 0) {
                return -2;
            }
        }
        return parent::delete($object, $related_field);
    }
    function get_list_category_child($id){
    	$rs=$this->db->select('code,title,id')->where('parent_id',$id)->get('category');
    	return $rs->result();
    }  
    
    
    function get_name($code){
    	$category = new Category_model();
    	$category->select('title')->where('code',$code)->get();
    	return $category;
    }
    
    function get_title_by_category_id_list($category_id_list){
    	 $this->select("id, title");
         
         $i = 0;
         foreach($category_id_list as $c)
         {
             if($i == 0)
                $this->where('id',$c);
             else
                 $this->or_where('id',$c);
             $i++;
         }
    	 //$this->where_in("id", $category_id_list);
    	 $this->get();
//     	 $this->check_last_query();
//     	 exit;
//     	 $array = array();
//     	 foreach($this as $item){
//     	 	$array[$item->id] = $item->title;	
//     	 }
//     	 print_r($array);
//     	 exit;
         //echo $this->db->last_query();exit;
		return $this;
    }
    
    function total(){
    	$this->select("count(id) as total");
    	$this->get();
    	
		return array(
					"title" => $this->lang->line('category'),
					"total"	=> $this->total,
				);	
    }
    function get_all_id()
    {
        return $this->get();
    }
    
    function get_news($limit = 10, $page = 0) {
        if ($this->id > 0) {
            $news = new News_model();
            $news->select('id, code, title,description,image, link, created, content');
            $news->where('active', 1); 
            $news->where_related('category', 'id', $this->id);
            $news->include_related('category', array('code','title'));
            $news->order_by('created', 'desc');
            return $news->get_paged_iterated($page, $limit);
        }
        return new News();
    }
}

/* End of file news_model.php */
/* Location: ./application/models/news_model.php */